<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>登录/注册 - 二手平台</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
    <h2>用户登录</h2>
    <form id="loginForm">
        <input type="text" id="loginUsername" placeholder="用户名" required>
        <input type="password" id="loginPassword" placeholder="密码" required>
        <button type="submit">登录</button>
    </form>
    <hr>
    <h2>用户注册</h2>
    <form id="registerForm">
        <input type="text" id="registerUsername" placeholder="用户名" required>
        <input type="password" id="registerPassword" placeholder="密码" required>
        <button type="submit">注册</button>
    </form>
    <div id="msg"></div>
</div>
<script src="js/api.js"></script>
<script>
    // 登录
    document.getElementById('loginForm').onsubmit = async function(e) {
        e.preventDefault();
        const username = document.getElementById('loginUsername').value;
        const password = document.getElementById('loginPassword').value;
        const formData = new URLSearchParams();
        formData.append('username', username);
        formData.append('password', password);
        const resp = await fetch('/api/auth/login', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: formData
        });
        if (resp.ok) {
            window.location.href = '/index.html';
        } else {
            document.getElementById('msg').innerText = '登录失败，请检查用户名或密码';
        }
    };

    // 注册
    document.getElementById('registerForm').onsubmit = async function(e) {
        e.preventDefault();
        const username = document.getElementById('registerUsername').value;
        const password = document.getElementById('registerPassword').value;
        const resp = await apiRegister(username, password);
        if (resp.ok) {
            document.getElementById('msg').innerText = '注册成功，请登录';
        } else {
            document.getElementById('msg').innerText = '注册失败，用户名可能已存在';
        }
    };
</script>
</body>
</html>